<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Post extends CI_Controller
{
    private $user_id;
	function __construct()
	{
		parent::__construct();
        $this->load->config('layout', TRUE);
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$this->load->library('security');
		$this->load->library('tank_auth');
		$this->load->library('backyard_view');
        $this->load->library('houseme_view');
        $this->load->library('facebook');
		$this->lang->load('tank_auth');
		$this->lang->load('backyard');
        $this->load->model('post_model');
        $this->user_id = $this->session->userdata('user_id');
	}

	function index(){}

    function detail(){//show post detail
        $post_id = $this->uri->segment(3);
        $data = array();
        $data = $this->input->get(); // returns all GET items with XSS filter

        $data['post'] = $this->post_model->get_post_by_id($post_id);

        if(isset($data['q'])){
            $data['keyword'] = urldecode($data['q']);
            $data['previous_next_post'] = $this->post_model->get_previous_next_by_current_id_and_keyword($post_id,$data['keyword']);
        }
        elseif(isset($data['c'])){
            $data['category_id'] = $data['c'];
            $temp = array();
            $temp['category'] = $this->config->item('category', 'layout');
            $category_string = $temp['category'][$data['category_id']];
            $data['previous_next_post'] = $this->post_model->get_previous_next_by_current_id_and_category_string($post_id,$category_string);
        }
        else{
            $data['previous_next_post'] = $this->post_model->get_previous_next_by_current_id($post_id);
        }


        // get related post
        // 1) same category
        $data['related_post'] = $this->post_model->get_related_post_by_current_post($data['post']);
        
        
        //echo "<pre>";print_r($data);echo "</pre>";exit;
        $data['category'] = $this->config->item('category', 'layout');
        $data['login_area'] = $this->load->view('houseme/login_area', '', true);
        $this->load->view('houseme/post', $data);
    }

    function new_post(){
        
        //echo "<pre>";print_r($post_data['upload_image']);echo "</pre>";
        $data['post_type'] = 'post_new';
        $data['user_id'] = $this->user_id;
        
        // set login rules
        $this->form_validation->set_rules('post_category', 'Category', 'trim|required|xss_clean|strip_tags');
        $this->form_validation->set_rules('post_title', 'Title', 'trim|xss_clean|strip_tags');
        $this->form_validation->set_rules('post_desc', 'Desc', 'trim|required');
        $this->form_validation->set_rules('post_excerpt', 'Excerpt', 'trim|xss_clean|strip_tags|required');
        $this->form_validation->set_rules('post_tags', 'Tags', 'trim|required|xss_clean|strip_tags');

        $post_data = $this->input->post();

        $data['errors'] = array();
        if ($this->form_validation->run()) { // validate ok
                        
            //echo "<pre>";print_r($post_data['upload_image']);echo "</pre>";exit;
            if(!isset($post_data['upload_image'])){ // at least one image
                $data['errors']['upload_image'] = $this->lang->line('at_least_one_image');
                $data['image_uploader'] = $this->load->view('backyard/image_uploader', $data,true);
            }
            else{ // validate & image both ok
                if($this->post_model->save($post_data,$data['user_id'])){ // save ok
                    $this->move_images($post_data['upload_image']); 
                }

                $this->form_validation->_field_data = array(); // unset validated data
                $this->session->set_flashdata('action_msg', '文章新增成功');
                redirect('/backyard/all_post');
            }
            
        }
        else{ // validate fail
            if(!isset($post_data['upload_image'])){ // at least one image
                $data['errors']['upload_image'] = $this->lang->line('at_least_one_image');
                $data['image_uploader'] = $this->load->view('backyard/image_uploader', $data,true);
            }
            else{
                //echo "<pre>";print_r($post_data['upload_image']);echo "</pre>";
                $data['upload_image'] = $post_data['upload_image'];
                $data['image_uploader'] = $this->load->view('backyard/image_uploader_error', $data,true);
            }
        }

        $data['category'] = $this->post_model->get_post_category();
        $data['post_category'] = $this->load->view('backyard/post_category', $data,true);
        $this->load->view('backyard/post_new', $data);

    }

    function modify(){
        $data['post_type'] = 'post_new';
        $data['user_id'] = $this->user_id;
        
        // set login rules
        $this->form_validation->set_rules('post_category', 'Category', 'trim|required|xss_clean|strip_tags');
        $this->form_validation->set_rules('post_title', 'Title', 'trim|xss_clean|strip_tags');
        $this->form_validation->set_rules('post_desc', 'Desc', 'trim|required');
        $this->form_validation->set_rules('post_excerpt', 'Excerpt', 'trim|xss_clean|strip_tags|required');
        $this->form_validation->set_rules('post_tags', 'Tags', 'trim|required|xss_clean|strip_tags');

        $this->form_validation->set_rules('post_id', 'Post ID', 'trim|required'); //just validate not show up on page

        $post_data = $this->input->post();

        $data['errors'] = array();
        if ($this->form_validation->run()) { // validate ok
            

            if(!isset($post_data['upload_image'])){ // at least one image
                $data['errors']['upload_image'] = $this->lang->line('at_least_one_image');
                $data['image_uploader'] = $this->load->view('backyard/image_uploader', $data,true);
            }
            else{ // validate & image both ok
                if($this->post_model->modify($post_data,$post_data['post_id'])){ // modify ok
                    $this->move_images($post_data['upload_image']); 
                }

                $this->form_validation->_field_data = array(); // unset validated data
                $this->session->set_flashdata('action_msg', '文章修改成功');
                redirect('/backyard/all_post');
            }
            
        }
        else{ // validate fail
            if(!isset($post_data['upload_image'])){ // at least one image
                $data['errors']['upload_image'] = $this->lang->line('at_least_one_image');
                $data['image_uploader'] = $this->load->view('backyard/image_uploader', $data,true);
            }
            else{
                //echo "<pre>";print_r($post_data['upload_image']);echo "</pre>";
                
                $data['upload_image'] = $post_data['upload_image'];
                if($data['upload_image'] != ''){
                    $this->copy_images_to_temp($data['upload_image']);
                }
                $data['image_uploader'] = $this->load->view('backyard/image_uploader_error', $data,true);
            }
        }
        $data['post_id'] = $post_data['post_id'];
        $data['category'] = $this->post_model->get_post_category();
        $data['post_category'] = $this->load->view('backyard/post_category', $data,true);
        $this->load->view('backyard/post_modify', $data);
    }

    function save_as_draft(){
        
        //echo "<pre>";print_r($post_data['upload_image']);echo "</pre>";
        $data['post_type'] = 'post_new';
        $data['user_id'] = $this->user_id;
        
        // set login rules
        $this->form_validation->set_rules('post_category', 'Category', 'trim|xss_clean|strip_tags');
        $this->form_validation->set_rules('post_title', 'Title', 'trim|xss_clean|strip_tags');
        $this->form_validation->set_rules('post_desc', 'Desc', 'trim');
        $this->form_validation->set_rules('post_excerpt', 'Excerpt', 'trim|xss_clean|strip_tags');
        $this->form_validation->set_rules('post_tags', 'Tags', 'trim|xss_clean|strip_tags');

        $post_data = $this->input->post();

        $data['errors'] = array();
        if ($this->form_validation->run()) { // validate ok
                        
            if(!isset($post_data['post_id'])){ // save as draft from post
                if($this->post_model->save($post_data,$data['user_id'],'0')){ // save ok
                    if(isset($post_data['upload_image'])){
                        $this->move_images($post_data['upload_image']); 
                    }
                }
            }
            else{ // save as draft from modify
                if($this->post_model->modify($post_data,$post_data['post_id'],'0')){ // modify ok
                    $this->move_images($post_data['upload_image']); 
                }
            }
            

            $this->form_validation->_field_data = array(); // unset validated data
            $this->session->set_flashdata('action_msg', '文章已存為草稿');
            redirect('/backyard/all_post');
            
        }
        else{ // validate fail
            $data['upload_image'] = $post_data['upload_image'];
            $data['image_uploader'] = $this->load->view('backyard/image_uploader_error', $data,true);
        }

        $data['category'] = $this->post_model->get_post_category();
        $data['post_category'] = $this->load->view('backyard/post_category', $data,true);
        $this->load->view('backyard/post_new', $data);

    }

    function delete(){
        sleep(1);
        $post_data = $this->input->post();
        if($this->post_model->delete($post_data['post_id'])){
            $data['msg'] =  '文章刪除成功';
        }
        else{
            $data['msg'] = '文章刪除失敗，請稍候再試，或洽出張嘴';
        }

        echo json_encode($data);
    }


    function move_images($filenames) // move images from temp to original and thumbs directory // and clean temp
    {
        $user_id = $this->user_id;
        $tempDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_temp', 'layout').$user_id.'/';
        $originalImageDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_original', 'layout').$user_id.'/';
        $thumbsImageDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_thumbs', 'layout').$user_id.'/';
        if (!is_writable($originalImageDirectory)){
            mkdir($originalImageDirectory);
        }
        
        if (!is_writable($thumbsImageDirectory)){
            mkdir($thumbsImageDirectory);
        }
        
        foreach($filenames as $filename){
            @rename($tempDirectory.$filename, $originalImageDirectory.$filename);// move to original
            @rename($tempDirectory.'thumbs_'.$filename, $thumbsImageDirectory.$filename);// move to thumbs
        }
        
        // clean temp for rubbish images
        $this->rrmdir($tempDirectory);
        
        return;
    }
    
    function copy_images_to_temp($filenames) // move images from temp to original and thumbs directory // and clean temp
    {
        $user_id = $this->user_id;
        $tempDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_temp', 'layout').$user_id.'/';
        $originalImageDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_original', 'layout').$user_id.'/';
        $thumbsImageDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_thumbs', 'layout').$user_id.'/';
        if (!is_writable($tempDirectory)){
            @mkdir($tempDirectory);
        }
    
        foreach($filenames as $filename){
            @copy($originalImageDirectory.$filename,$tempDirectory.$filename);// move from original to temp
            @copy($thumbsImageDirectory.$filename,$tempDirectory.'thumbs_'.$filename);// move from thumbs to temp
        }
        
        return;
    }
    
    function rrmdir($dir) { 
       if (is_dir($dir)) { 
         $objects = scandir($dir); 
         foreach ($objects as $object) { 
           if ($object != "." && $object != "..") { 
             if (filetype($dir."/".$object) == "dir") $this->rrmdir($dir."/".$object); else unlink($dir."/".$object); 
           } 
         } 
         reset($objects); 
         rmdir($dir); 
       } 
    }
}

/* End of file backyard.php */
/* Location: ./application/controllers/backyard.php */